//
//  YTBonjourClient.m
//  YTBonjourKit
//
//  Created by aron on 2020/8/13.
//

#import "YTBonjourClient.h"
#import "YTNetServiceModel.h"

@interface YTBonjourClient ()<NSNetServiceBrowserDelegate>
@property (nonatomic, strong) NSNetServiceBrowser *browser;

@property (nonatomic, strong) NSMutableArray *availableService;

@end

@implementation YTBonjourClient

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.availableService = [NSMutableArray new];
        self.browser = [[NSNetServiceBrowser alloc] init];
        self.browser.delegate = self;
    }
    return self;
}

// MARK: - Public

+ (instancetype)sharedInstance {
    static YTBonjourClient *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [YTBonjourClient new];
    });
    return instance;
}

// self.netService = [[NSNetService alloc] initWithDomain:@"local." type:@"_http._tcp." name:name port:62323];
- (void)startFindService {
    [self.availableService removeAllObjects];
    [self stopFindService];
    [self.browser searchForServicesOfType:@"_http._tcp." inDomain:@"local."];
}

- (void)stopFindService {
    [self.browser stop];
}


// MARK: - NSNetServiceBrowserDelegate

- (void)netServiceBrowserWillSearch:(NSNetServiceBrowser *)browser {
    NSLog(@"====netServiceBrowserWillSearch");
}

- (void)netServiceBrowserDidStopSearch:(NSNetServiceBrowser *)browser {
    NSLog(@"====netServiceBrowserDidStopSearch");
}

- (void)netServiceBrowser:(NSNetServiceBrowser *)browser didNotSearch:(NSDictionary<NSString *, NSNumber *> *)errorDict {
    NSLog(@"====didNotSearch");
}

- (void)netServiceBrowser:(NSNetServiceBrowser *)browser didFindDomain:(NSString *)domainString moreComing:(BOOL)moreComing {
    NSLog(@"====didFindDomain");
}

- (void)netServiceBrowser:(NSNetServiceBrowser *)browser didFindService:(NSNetService *)service moreComing:(BOOL)moreComing
{
    NSString *str = [[NSString alloc] initWithData:[service TXTRecordData] encoding:NSUTF8StringEncoding];
    NSLog(@"====find %@", [service name]);

    YTNetServiceModel *serviceModel = [YTNetServiceModel new];
    serviceModel.netService = service;
    serviceModel.serviceName = service.name;
    [self.availableService addObject:serviceModel];
}

- (void)netServiceBrowser:(NSNetServiceBrowser *)browser didRemoveDomain:(NSString *)domainString moreComing:(BOOL)moreComing {
    
}

- (void)netServiceBrowser:(NSNetServiceBrowser *)browser didRemoveService:(NSNetService *)service moreComing:(BOOL)moreComing {
    
}

@end
